package com.cts.tmall.biz.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.TmallFile;
import com.cts.tmall.dal.mapper.TmallFileMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 文件上传下载
 *
 * @author leibing.song
 */
@Slf4j
@Service
public class FileService {

    @Autowired
    private TmallFileMapper fileMapper;

    @Value("${file.dir}")
    private String basePath;

    public TmallFile upload(String fileName, String fileType) {
        TmallFile dbFile = new TmallFile();
        dbFile.setFileName(fileName);
        dbFile.setFileType(fileType);
        dbFile.setFilePath(basePath);
        int insertCount = fileMapper.insert(dbFile);
        if (insertCount != 1) {
            log.error("文件上传失败！");
            throw new SystemException(RspCode.FAILURE_SYSTEM, "文件上传失败！");
        }
        return dbFile;
    }

    public TmallFile download(Integer fileId) {
        if (fileId == null ||
                fileMapper.selectCount(Wrappers.<TmallFile>lambdaQuery().eq(TmallFile::getFileId, fileId)) != 1) {
            log.error("文件下载失败！文件不存在！");
            throw new SystemException(RspCode.FAILURE_SYSTEM, "文件下载失败！文件不存在！");
        }
        return fileMapper.selectById(fileId);
    }
}
